import {uploadFile} from '../../api/upload'
import {saveAvatarAndName} from '../../api/login'
import http from '../../utils/http'
Component({
  data:{
    userInfo:{},
    fileList:[],
    userFunctionList:[],
    myLists:[{
      
    }],
    imagePath: '', // 存储选中的图片路径
  },
  methods:{
    onShow(){
      // 我的功能分类
      const userType = getApp().getUserType()
      let teacherList =[
      //   {
      //   icon:"scan",
      //   title:"销课"
      // },
      {
        icon:"Document",
        title:"课程表",
        path:"/curriculum_package/pages/myCurriculum/myCurriculum" 
      },
      {
        icon:"Logout",
        title:"请假调课",
        path:"/leaveDate_package/pages/teacherLeaveDateRecord/teacherLeaveDateRecord" 
      },
      {
        icon:"record",
        title:"上课记录",
        path:"/teacher_course_package/pages/teacherClassRecords/teacherClassRecords"
      },  
      // {
      //   icon:"front",
      //   title:"学前评价",
      //   path:"/teacher_course_package/pages/ClassFrontEvaluation/ClassFrontEvaluation"
      // },{
      //   icon:"course",
      //   title:"课程评价",
      //   path:"/teacher_course_package/pages/ClassCourseEvaluation/ClassCourseEvaluation"
      // },{
      //     icon:"after",
      //     title:"结业评价",
      //     path:"/teacher_course_package/pages/ClassAfterEvaluation/ClassAfterEvaluation"
      // },
      {
        icon:"Shield",
        title:"设置",
        path:"/curriculum_package/pages/setting/setting"
      }
    ] as any
      let studentList = [{
        icon:"Document",
        title:"课程表",
        path:"/curriculum_package/pages/myCurriculum/myCurriculum"
      },{
        icon:"Wallet",
        title:"签到",
        path:"/signIn_package/pages/signInHome/signInHome"
      },{
        icon:"Logout",
        title:"请假调课",
        path:"/leaveDate_package/pages/leaveDate/leaveDate"
      },{
        icon:"Heart",
        title:"增加学员",
        path:"/curriculum_package/pages/addStudents/addStudents"
      },{
        icon:"Profile",
        title:"学员",
        path:"/curriculum_package/pages/studentsDetail/studentsDetail"

      },{
        icon:"Ticket",
        title:"购买记录",
        path:"/curriculum_package/pages/purchaseHistory/purchaseHistory"

      },{
        icon:"Notification",
        title:"消息",
        path:"/notify_package/pages/noticeSort/noticeSort"

      },{
        icon:"Shield",
        title:"设置",
        path:"/curriculum_package/pages/setting/setting"
      }
    ]  as any
      if(userType === '01'){
      this.setData({
        userFunctionList: teacherList
      })        
      }else{
        this.setData({
          userFunctionList: studentList
        })     
      }
      this.myList()
      this.getUserInfo()
    },
    onLoad(){

    },
        // 上传图片
  afterRead(event:any) {
    const { file } = event.detail; // 获取上传的文件对象
    const filePath = file.url; // 获取临时文件路径
    // 调用封装的上传函数
    uploadFile(filePath, 'testUser') // 替换为实际的用户信息
      .then((res) => {
        // 更新图片列表
        console.log("此时的照片",res);

        this.setData({
          fileList: [{ url: filePath }]
        });
        const {code,data} = JSON.parse( res.data as any)
        if(code === 200){
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          });

          const formData = this.data.formData as any
          
          formData.avatar = data
          this.setData({
            formData
          })
        }          
      })
      .catch((err) => {
        console.error('上传失败:', err);
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      });
  },
    getUserInfo(){
    const info = getApp().getUserInfo()
    const userInfo = {
      avatar:info.avatar,
      nickName:info.nickName,
      id:info.userId
    }
    this.setData({
      userInfo
    })
    this.setData({
      fileList:[{
        url: userInfo.avatar
      }]
    })
   
    },
    myList(){
     let newList = this.data.userFunctionList.map((val:any)=>{
        return {
          imgUrl:`/static/image/mySetting/${val.icon}.png`,
          title:val.title,
          path:val.path
        }
      })
      this.setData({
        myLists:newList
      })
    },
    skip(e:any){    
   const {path} = e.currentTarget.dataset
  if(path){
    wx.navigateTo({
      url:path
    })
  }else{
    wx.scanCode({
      success(res){
        console.log("扫码成功",res);
        
      }
    })
   
  }
    },
    // 更换头像
    changeAvatar(){
      wx.chooseMedia({
        count: 1, // 限制选择一张图片
        mediaType: ['image'], // 只允许选择图片
        sourceType: ['album', 'camera'], // 可从相册或相机选择
        sizeType: ['compressed'], // 选择压缩后的图片
        success: (res) => {
          const tempFilePath = res.tempFiles[0].tempFilePath;
          this.setData({
            imagePath: tempFilePath, // 用于展示预览图片
          });
          // 调用上传图片方法
          this.uploadImage(tempFilePath);
          
        },
        fail: (err) => {
          console.error("选择图片失败", err);
        },
      });
      
    },
    // 上传图片
  uploadImage(filePath:any) {
    wx.uploadFile({
      url:  `${http.baseURL}/user/student/avatar`, // 替换成你的服务器接口地址
      filePath: filePath,
      name: 'avatarfile', // 服务端接收图片的字段名
      // formData: {
      //   user: user, // 示例的额外参数
      // },
      header: {
        'Authorization': `Bearer ${getApp().getToken()}`, // 添加 Token 到请求头中
        'Content-Type': 'multipart/form-data' // 确保文件上传时的内容类型
      },
      success: (res) => {
        const result = JSON.parse( res.data as any)
        if(result.code === 200){
          wx.showToast({
            title: '头像上传成功',
            icon: 'success',
          });
          const userInfo = this.data.userInfo as any
          userInfo.avatar = result.data
          saveAvatarAndName({
            avatar:result.data,
            nickName:getApp().getUserInfo().nickName
          }).then(res=>{
            console.log(res);
            
          })
          this.setData({
            userInfo
          })
        }

      },
      fail: (err) => {
        console.error('上传失败', err);
        wx.showToast({
          title: '上传失败',
          icon: 'none',
        });
      }
    });
  }
  }
})